package com.easyfun.healthmagicbox.comm;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.content.Context;

import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.ormlite.ServerResponseCode;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.sync.BasicCommCallback;
import com.easyfun.healthmagicbox.sync.CommCallback;

public class SharePersonTask extends BaseCommTask implements Runnable,
		DatabaseAccess {
	String username;
	String invitecode;
	String personID;

	public SharePersonTask(String username, String personID, String sharecode, Context context,
			CommCallback callback) {

		super(context,callback);
		this.username = username;
		this.personID = personID;
		this.invitecode = sharecode;
	}

	@Override
	public DatabaseHelper getHelper(Context context) {

		return DatabaseAccessImplementation.getInstance().getHelper(mcontext);
	}

	@Override
	public void run() {

		JSONObject serializedObj = new JSONObject();
		String result = "";
		try {
			serializedObj.put("username", username);
			serializedObj.put("personID", personID);
			serializedObj.put("invitecode", invitecode);
			
			Map<String, String> parmas = new HashMap<String, String>();
			parmas.put("jsonstring", serializedObj.toString());
			result = super.uploadByHTTP(parmas, ConstantData.UserSharePersonURI);
			if (ServerResponseCode.parseOf(result) == ServerResponseCode.SUCCESS) {
				ccb.setCommResult(this, result,
						ServerResponseCode.SUCCESS);
				
				
				PersonProfileDownloadTask ppdtask = new PersonProfileDownloadTask(
						personID,
						mcontext,
						new BasicCommCallback());
				
				HealthThreadPool.getInstance().execute(ppdtask);
				
				HealthInputDataDownloadTask hiddtask = new HealthInputDataDownloadTask(
						mcontext, 
						personID, 
						new BasicCommCallback());
				HealthThreadPool.getInstance().execute(hiddtask);
				return;
			} 
			
			
			ccb.setCommResult(this, result,
					ServerResponseCode.FAILED);
			return;
			
		} catch (Exception e) {
			e.printStackTrace();
			ccb.setCommResult(this, result,
					ServerResponseCode.FAILED);
		}
	}
}
